<?php
/**
 * @package PWE.modele.menu
 * @author Gmax <gmaxfr78@gmail.com>
 */
class modele_menu extends modele{
    protected static $_table = 'menu';
    public $type = 'menu';
    private $_id;
    private $_identifiant;
    private $_items;
    
    function __construct($id=null,$getDefault=true){
        if($id!==null){
            if(is_int($id)){
                $this->_id = $id;
            }else{
                $this->_identifiant = $id;
            }
            $this->_constructObject($getDefault);
        }
    }
    
    private function _constructObject($getDefault=true){
        $sqlQuery = 'SELECT ';
        $sqlQuery .= 't.* ';
        $sqlQuery .= 'FROM '.self::getTable().' as t ';
        if($this->_id!==null) $sqlQuery .= 'WHERE t.id='.$this->_id.' ';
        else $sqlQuery .= 'WHERE t.identifiant="'.$this->_identifiant.'" ';
        $sqlQuery .= 'LIMIT 1';
        
        $datas = $this->_getOneResult($sqlQuery);
        
        if($datas){
            $this->_id = $datas['id'];
            $this->_identifiant = $datas['identifiant'];
        }elseif(!$getDefault){
            $this->_id = 0;
            $this->_identifiant = '';
        }
    }
    /**
     * renvoi les datas de la liste des item menu
     * @param boolean $input
     * @return array
     */
    public function getItems($input=false){
        $retour = array();
        $datas = modele_menu_item::getPrimaryListe($this->getId());
        foreach( $datas as $item ){
            if($item->getOrder()>0){
                $retour[$item->getOrder()] = $item->getDatas($input);
            }else{
                $retour[] = $item->getDatas($input);
            }
        }
        ksort($retour);
        return $retour;
    }
    /**
     * renvoi les datas traduits dans la langue courante de la liste des item menu
     * @param boolean $input
     * @return array
     */
    public function getTranslatedItems($lang='',$input=false){
        $retour = array();
        $datas = modele_menu_item::getPrimaryListe($this->getId());
        foreach( $datas as $item ){
            //$translator = new modele_translate($item->getId(),array('type'=>'object','lang'=>$lang,'modele'=>'menu_item'));
            $translator = new controler_translate();
            $translator->init($item, $lang);
            $translatedDatas = $translator->getDatas($input);
            $translatedDatas['url'] = $item->getTranslatedUrl($lang);
            
            if($item->getOrder()>0){
                $retour[$item->getOrder()] = $translatedDatas;
            }else{
                $retour[] = $translatedDatas;
            }
        }
        ksort($retour);
        return $retour;
    }
    
    public function getId(){
        return $this->_id;
    }
    public function getIdentifiant($input=false){
        if($input)return $this->inputFormat($this->_identifiant);
        else return $this->outputFormat($this->_identifiant);
    }
    public function getHtml($templateFile){
        if(file_exists($templateFile) ){
            ob_start();
            include($templateFile);
            $retour = ob_get_contents();
            ob_end_clean();
        }else{
            $retour = 'erreur de chargement du template : '.$templateFile;
        }
        return $retour;
    }
    public function setDatas($datas) {
        foreach($datas as $k=>$v){
            if($k != '_id' && property_exists(get_class($this),$k)){
                $this->$k = $v;
            }
        }
        return true;
    }
    public function getDatas($input=false){
        $data = array();
        $data['id'] = $this->getId();
        $data['identifiant'] = $this->getIdentifiant($input);
        $data['items'] = $this->getItems($input);
        return $data;
    }
    
    public function getTranslatedDatas($lang='',$input=false){
        $data = array();
        $data['id'] = $this->getId();
        $data['identifiant'] = $this->getIdentifiant($input);
        $data['items'] = $this->getTranslatedItems($lang,$input);
        return $data;
    }
    public function save() {
        $sqlQueryMenu = 'INSERT INTO '.self::getTable().' ';
        $sqlQueryMenu .= '(identifiant) ';
        $sqlQueryMenu .= 'VALUES ("'.$this->getIdentifiant(true).'")';
        bdd_sql::doSql($sqlQueryMenu,false);
        $this->_id = bdd_sql::getLastInsertId();
        
        return array('success'=>true,'datas'=>$this->getDatas());
    }
    public function update() {
        $sqlQueryMenu = 'UPDATE '.self::getTable().' SET identifiant="'.$this->getIdentifiant(true).'" WHERE id='.$this->getId().' LIMIT 1';
        bdd_sql::doSql($sqlQueryMenu,false);
        $listeItem = modele_menu_item::getPrimaryListe($this->getId());
        foreach( $listeItem as $item ){
            $destroy = true;
            foreach($this->_items as $idx=>$newItem){
                if( isset($newItem['id']) && $newItem['id'] === $item->getId() ){
                    if((!isset($newItem['label'])||$newItem['label']==='') && (!isset($newItem['title'])||$newItem['title']==='') && (!isset($newItem['link'])||$newItem['link']==='')){
                        unset($this->_items[$idx]);
                        $destroy = true;
                    }else{
                        $item->setDatas($newItem);
                        $item->update();
                        unset($this->_items[$idx]);
                        $destroy = false;
                    }
                }
            }
            if($destroy){
                $item->delete();
            }
        }
        
        foreach($this->_items as $idx=>$nItem){
            if(isset($nItem['label']) && $nItem['label']!==''){
                $item = new modele_menu_item();
                $item->setDatas($nItem);
                $item->save();
                unset($this->_items[$idx]);
            }
        }
        $this->_items = null;
        return array('success'=>true,'datas'=>$this->getDatas());
    }
    
    public function delete(){
        $listeItem = modele_menu_item::getListe($this->getId());
        foreach( $listeItem as $item ){
            $item->delete();
        }
        $sqlQuery = 'DELETE FROM '.self::getTable().' WHERE id='.$this->getId().' LIMIT 1';
        bdd_sql::doSql($sqlQuery,false);
        return array('success'=>true,'datas'=>array());
    }
    
    /* methodes statiques */
    /**
     * 
     * @return string
     */
    public static function getTable(){
        return PWE::getPrefixBdd().self::$_table;
    }
    
    /**
     * 
     * @param int $start
     * @return \modele_menu
     */
    public static function getListe($start = 0, $limit = 0){
        $sqlQuery = 'SELECT id FROM '.self::getTable().' ORDER BY id DESC';
        
        if($limit>0){
            $sqlQuery .=  ' LIMIT '.$start.', '.$limit;
        }
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        if($results['count']>0){
            foreach($results['results'] as $categoryData){
                $retour[] = new modele_menu($categoryData['id']+0);
            }
        }
        return $retour;
    }
    
    /**
     * 
     * @param string $identifiant
     * @return \modele_menu|null
     */
    public static function isMenuExists($identifiant){
        $sqlQuery = 'SELECT ';
        $sqlQuery .= 't.* ';
        $sqlQuery .= 'FROM '.self::getTable().' as t ';
        $sqlQuery .= 'WHERE t.identifiant="'.$identifiant.'" ';
        $sqlQuery .= 'LIMIT 1';
        
        $datas = bdd_sql::doSql($sqlQuery,true);
        
        if($datas['count']===1){
            return new modele_menu($datas['results'][0]['id']+0);
        }else{
            return null;
        }
    }
    
    /**
     * 
     * @param string $lien
     * @param string $identifiantMenu
     * @return \modele_menu_item
     */
    public static function findItemByPermalien($lien,$identifiantMenu=''){
        $sql = 'SELECT mi.id AS id FROM '.modele_menu_item::getTable().' AS mi ';
        if($identifiantMenu!==''){
            $sql .= 'LEFT JOIN '.self::getTable().' AS m ON m.id = mi.menu_id ';
        }
        $sql .= 'WHERE mi.link="'.$lien.'"';
        if($identifiantMenu!==''){
            $sql .= ' AND m.identifiant="'.$identifiantMenu.'"';
        }
        $retour = array();
        $results = bdd_sql::doSql($sql, true, true);
        if($results['count']>0){
            foreach($results['results'] as $data){
                $retour[] = new modele_menu_item($data['id']);
            }
        }
        
        return $retour;
    }
}